/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package dao

import (
	"fmt"
	"prim-server/common"
	"prim-server/model"

	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
	"github.com/spf13/cast"
)

type OnDemandOrderDao struct {
	BaseDao
}

type IOnDemandOrderDao interface {
	//保存数据--单条数据/多条数据
	SaveOnDemandOrderInfo(order []*model.OnDemandOrder) error
	//删除指定分表数据
	DeleteOnDemandOrderInfo(orderId string) error
	//更新指定分表数据
	UpdateOnDemandOrderInfo(order *model.OnDemandOrder) error
	//查询指定分表数据
	GetOnDemandOrderInfo(queryParameter *common.QueryOnDemandOrderDetail) (orders []*model.OnDemandOrder, totalCount int, err error)
}

func GetOnDemandOrderao() IOnDemandOrderDao {
	dao := &OnDemandOrderDao{}
	dao.Init()
	return dao
}

func (od *OnDemandOrderDao) SaveOnDemandOrderInfo(order []*model.OnDemandOrder) error {
	if len(order) == 0 {
		return nil
	}
	if len(order) == 1 {
		_, err := od.O.Insert(order[0])
		if err != nil {
			return errors.Errorf("SaveOnDemandOrderInfo error: %v, on-demand orderId: %s", err, order[0].OrderId)
		}
	} else {
		_, err := od.O.InsertMulti(len(order), order)
		if err != nil {
			_ = od.O.Rollback()
			return errors.Errorf("SaveOnDemandOrderInfo error: %v, on-demand size: %v", err, len(order))
		}
	}
	return nil
}
func (od *OnDemandOrderDao) DeleteOnDemandOrderInfo(orderId string) error {
	if len(orderId) == 0 {
		return nil
	}
	order := new(model.OnDemandOrder)
	order.OrderId = orderId
	_, err := od.O.Delete(order, "order_id")
	if err != nil {
		_ = od.O.Rollback()
		return errors.Errorf("DeleteOnDemandOrderInfo error: %v, on-demand orderId: %s", err, orderId)
	}
	return nil
}
func (od *OnDemandOrderDao) UpdateOnDemandOrderInfo(OnDemandOrder *model.OnDemandOrder) error {
	if OnDemandOrder == nil {
		return nil
	}
	_, err := od.O.Update(OnDemandOrder)
	if err != nil {
		_ = od.O.Rollback()
		return errors.Errorf("UpdateOnDemandOrderInfo error: %v, on-demand orderId: %s", err, OnDemandOrder.OrderId)
	}
	return nil
}

func (od *OnDemandOrderDao) buildParameterForGetOnDemandOrderInfo(queryParameter *common.QueryOnDemandOrderDetail) *orm.Condition {
	finalCondition := orm.NewCondition()
	if len(queryParameter.OrderId) > 0 {
		finalCondition = finalCondition.And("order_id__in", queryParameter.OrderId)
	}
	if len(queryParameter.PlatformType) > 0 {
		finalCondition = finalCondition.And("platform_type__in", queryParameter.PlatformType)
	}
	if len(queryParameter.OrderType) > 0 {
		finalCondition = finalCondition.And("order_type__in", queryParameter.OrderType)
	}
	if len(queryParameter.ResourceId) > 0 {
		finalCondition = finalCondition.And("resource_id__in", queryParameter.ResourceId)
	}
	if len(queryParameter.UserId) > 0 {
		finalCondition = finalCondition.And("user_id__in", queryParameter.UserId)
	}
	if len(queryParameter.CloudUserId) > 0 {
		finalCondition = finalCondition.And("cloud_user_id__in", queryParameter.CloudUserId)
	}
	if queryParameter.CreatedTimeBegin != nil && queryParameter.CreatedTimeEnd != nil {
		createdTimeCondition := orm.NewCondition()
		createdTimeCondition = createdTimeCondition.And("created_time__gte", od.ConvertToUTC(*queryParameter.CreatedTimeBegin)).And("created_time__lte", od.ConvertToUTC(*queryParameter.CreatedTimeEnd))
		finalCondition = finalCondition.AndCond(createdTimeCondition)
	}
	return finalCondition
}

func (od *OnDemandOrderDao) GetOnDemandOrderInfo(queryParameter *common.QueryOnDemandOrderDetail) (orders []*model.OnDemandOrder, totalCount int, err error) {
	if queryParameter == nil {
		return nil, 0, nil
	}
	recode := od.O.QueryTable(&model.OnDemandOrder{})
	finalCondition := od.buildParameterForGetOnDemandOrderInfo(queryParameter)
	offset, pageSize := od.GetOffsetAndPageSize(queryParameter.Page, queryParameter.PageSize)
	//the order of created_id and created_time is equal
	if queryParameter.TimeReverseOrder == nil {
		recode = recode.OrderBy("-created_time")
	} else {
		if !(*queryParameter.TimeReverseOrder) {
			recode = recode.OrderBy("created_time")
		}
	}
	recode = recode.SetCond(finalCondition)
	totalCount64, err := recode.Count()
	if err != nil {
		return nil, 0, errors.Errorf("GetOnDemandOrderInfo error: %v, userId: %s", err, fmt.Sprint(queryParameter.UserId))
	}
	totalCount = cast.ToInt(totalCount64)
	_, err = recode.Offset(offset).Limit(pageSize).All(&orders)
	if err != nil {
		if err == orm.ErrNoRows {
			//not found
			return nil, 0, nil
		}
		//found error
		return nil, 0, errors.Errorf("GetOnDemandOrderInfo error: %v, userId: %s", err, fmt.Sprint(queryParameter.UserId))
	}
	return orders, totalCount, nil
}
